package mydessertstore.web.servlet;

import mydessertstore.domain.Account;
import mydessertstore.domain.Cart;
import mydessertstore.domain.Item;
import mydessertstore.domain.Product;
import mydessertstore.service.CatalogService;
import mydessertstore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AddItemToCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset = UTF-8");

        String workingItemId = req.getParameter("workingItemId");
        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        String flaginRequest = req.getParameter("flag");
        Integer flaginSession = (Integer)session.getAttribute("flag");
        String sessionFlag = flaginSession.toString();

        System.out.println("jsp的flag值"+flaginRequest+"session传过来的："+sessionFlag);
        if(sessionFlag.equals(flaginRequest)) {
            if (cart == null) {
                cart = new Cart();
            }


            if (cart.containsItemId(workingItemId)) {
                cart.incrementQuantityByItemId(workingItemId);

            } else {
                CatalogService catalogService = new CatalogService();
                boolean isInStock = catalogService.isItemInStock(workingItemId);
                Item item = catalogService.getItem(workingItemId);
                System.out.println("找到的是"+item.getItemId());
                cart.addItem(item, isInStock);

                //日志输出到数据库
                    Account account;
                    account=(Account) session.getAttribute("account");
                    if(account!=null) {
                        LogService logService = new LogService();
                        String logInfo = logService.logInfo(" ") + " 添加物品 " + item + " 到购物车";
                        logService.insertLogInfo(account.getUsername(), logInfo);
                    }
                    else{
                        LogService logService = new LogService();
                        String logInfo = logService.logInfo(" ") + " 添加物品 " + item + " 到购物车";
                        logService.insertLogInfo("未登录用户", logInfo);
                    }


            }

            session.setAttribute("cart", cart);

            //操作完以后修改session，这样刷新的话不会从jsp得到flag为1的session，就没办法再操作
            session.setAttribute("flag",0);
            req.getRequestDispatcher(CART_FORM).forward(req, resp);
        }else{
            req.getRequestDispatcher(CART_FORM).forward(req, resp);
        }
    }
}
